package com.can.Config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.can.Mapper.PostMapper;
import com.can.Mapper.GoodBadMapper;
import com.can.domain.po.Goodbad;
import com.can.domain.po.post;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PostLikeCacheInitializer {
    @Autowired
    PostMapper postMapper;
    @Autowired
    GoodBadMapper goodbadMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

//    项目启动时，加载所有点赞/踩数据到 Redis
    @PostConstruct
    public void initPostLikeCache() {
        try {
            redisTemplate.getConnectionFactory().getConnection().flushAll();
            System.out.println("清空redis成功");
        }catch (Exception e){
            System.out.println("清空redis失败");
        }

            List<Goodbad> res = goodbadMapper.selectList(null);
            for (Goodbad gd : res) {
                String goodKey = "post:" + gd.getPostId() + ":good";
                String badKey = "post:" + gd.getPostId() + ":bad";
                // 存入 Redis（如果已存在则覆盖）
                redisTemplate.opsForValue().set(goodKey, String.valueOf(gd.getGood()));
                redisTemplate.opsForValue().set(badKey, String.valueOf(gd.getBad()));
            }

        System.out.println("✅ 帖子点赞数据已全量缓存至 Redis");
    }
}


